package com.qidianit.mes.sys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidianit.mes.pojo.Result;
import com.qidianit.mes.pojo.Supplier;
import com.qidianit.mes.sys.mapper.SupplierMapper;
import com.qidianit.mes.sys.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 供应商服务实现类
 */
@Service
public class SupplierServiceImpl implements SupplierService {

    @Autowired
    private SupplierMapper supplierMapper;

    /**
     * 分页查询供应商列表
     */
    @Override
    public Result<PageInfo<Supplier>> selectList(Supplier supplier, int pageNum, int pageSize) {
        try {
            // 开启分页
            PageHelper.startPage(pageNum, pageSize);
            // 执行查询
            List<Supplier> supplierList = supplierMapper.selectList(supplier);
            // 封装分页信息
            PageInfo<Supplier> pageInfo = new PageInfo<>(supplierList);
            return Result.success(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据编码查询供应商
     */
    @Override
    public Result<Supplier> selectByCode(String code) {
        try {
            if (code == null || code.trim().isEmpty()) {
                return Result.error("供应商编码不能为空");
            }
            Supplier supplier = supplierMapper.selectByCode(code);
            if (supplier != null) {
                return Result.success(supplier);
            } else {
                return Result.error("未找到该供应商");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 新增供应商
     */
    @Override
    @Transactional
    public Result saveSupplier(Supplier supplier) {
        try {
            // 校验必填字段
            if (supplier.getCode() == null || supplier.getCode().trim().isEmpty()) {
                return Result.error("供应商编码不能为空");
            }
            if (supplier.getName() == null || supplier.getName().trim().isEmpty()) {
                return Result.error("供应商名称不能为空");
            }

            // 检查编码是否已存在
            Supplier existSupplier = supplierMapper.selectByCode(supplier.getCode());
            if (existSupplier != null) {
                return Result.error("供应商编码已存在");
            }

            // 设置默认值
            if (supplier.getStatus() == null) {
                supplier.setStatus(1); // 默认启用
            }
            supplier.setDeleteFlag(0); // 默认未删除
            supplier.setCreateTime(LocalDateTime.now());
            supplier.setUpdateTime(LocalDateTime.now());

            // 执行新增
            int rows = supplierMapper.saveSupplier(supplier);
            if (rows > 0) {
                return Result.success("新增成功");
            } else {
                return Result.error("新增失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("新增供应商异常：" + e.getMessage());
        }
    }

    /**
     * 更新供应商信息
     */
    @Override
    @Transactional
    public Result updateById(Supplier supplier) {
        try {
            // 校验ID
            if (supplier.getId() == null) {
                return Result.error("供应商ID不能为空");
            }

            // 检查编码是否重复（排除当前记录）
            Supplier existSupplier = supplierMapper.selectByCode(supplier.getCode());
            if (existSupplier != null && !existSupplier.getId().equals(supplier.getId())) {
                return Result.error("供应商编码已存在");
            }

            // 设置更新时间
            supplier.setUpdateTime(LocalDateTime.now());

            // 执行更新
            int rows = supplierMapper.updateById(supplier);
            if (rows > 0) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败，未找到该供应商或数据未变更");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("更新供应商异常：" + e.getMessage());
        }
    }

    /**
     * 逻辑删除供应商
     */
    @Override
    @Transactional
    public Result deleteById(Long id) {
        try {
            if (id == null) {
                return Result.error("供应商ID不能为空");
            }

            int rows = supplierMapper.deleteById(id);
            if (rows > 0) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败，未找到该供应商");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("删除供应商异常：" + e.getMessage());
        }
    }

    /**
     * 批量逻辑删除供应商
     */
    @Override
    @Transactional
    public Result batchDelete(Long[] ids) {
        try {
            if (ids == null || ids.length == 0) {
                return Result.error("请选择要删除的供应商");
            }

            int rows = supplierMapper.batchDelete(ids);
            if (rows > 0) {
                return Result.success("成功删除" + rows + "条记录");
            } else {
                return Result.error("删除失败，未找到选中的供应商");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("批量删除供应商异常：" + e.getMessage());
        }
    }
}
